package com.boyinet.activation.util;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author lengchunyun
 */
@Component
public class TokenManager {
    private final long tokenExpiration = 24 * 60 * 60 * 1000;
    private final String tokenSignKey = "123456";

    public String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
    }

    public String getUserFromToken(String token) throws BadCredentialsException {
        String username;
        try {
            username = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        } catch (Exception e) {
            throw new BadCredentialsException(e.getMessage());
        }
        return username;
    }

    public void removeToken(String token) {
    }
}
